import './style.css';
import PieChart from './components/PieChart/PieChart.js';
import InfoBarList from './components/InfoBarList/InfoBarList.js';
import WeatherBox from './components/WeatherBox/WeatherBox.js';
import TimeLine from './components/TimeLine/TimeLine.js';
import Legend from './components/Legend/Legend.js';
import Popup from './components/Popup/Popup.js';

// init minemap
minemap.domainUrl = '//minedata.cn';
minemap.spriteUrl = '//minedata.cn/minemapapi/v1.3/sprite/sprite';
minemap.serviceUrl = '//minedata.cn/service';
minemap.accessToken = 'a3622f2702c34957a160242d2eb0e508';
minemap.solution = 3756;

var map = new minemap.Map({
    container: 'map',
    style: "//minedata.cn/service/solu/style/id/3756",
    center: [108.95, 34.27],
    zoom: 12,
    pitch: 0,
    maxZoom: 17,
    minZoom: 10
});

map.repaint = true;

let pid = -1;
const backgroundId = 'e9424af07d8242adb4fa49abe40544b4';
const topId = 'road-highlight';
// const oldId = 'b519feeafff3466091df41876924bf21';

const popup = new minemap.Popup({
    offset: [0, -5]
}).addTo(map);

map.on('load', function () {
    document.getElementsByClassName('minemap-ctrl')[0].parentElement.innerHTML = '';    

    map.addSource("weather", {
        "type": "vector",
        'tiles': ['http://203.81.245.38:48082/weather/roadweather/{z}/{x}/{y}']
    });

    map.addLayer({
        "id": "pre",
        "type": "line",
        "source": "weather",
        "source-layer": "RoadWeather",
        "layout": {
            "line-join": "round",
            "line-cap": "round"
        },
        "paint": {
            "line-color": {
                "property": "precipitation0",
                "stops": [
                    [0, '#28AD86'],
                    [10, '#28AD86'],
                    [11, '#E0B62C'],
                    [25, '#E0B62C'],
                    [26, '#FE4B3C'],
                    [50, '#FE4B3C'],
                    [51, '#8E71FF']
                ]
            },
            "line-width": 6
        }
    }, 'e9424af07d8242adb4fa49abe40544b4');

    map.addLayer({
        "id": "tem",
        "type": "line",
        "source": "weather",
        "source-layer": "RoadWeather",
        "layout": {
            "line-join": "round",
            "line-cap": "round"
        },
        "paint": {
            "line-color": {
                "property": "TEM",
                "stops": [
                    [0, '#28AD86'],
                    [10, '#28AD86'],
                    [11, '#E0B62C'],
                    [25, '#E0B62C'],
                    [26, '#FE4B3C'],
                    [30, '#FE4B3C'],
                    [31, '#8E71FF'],
                ]
            },
            "line-width": 6
        }
    }, 'e9424af07d8242adb4fa49abe40544b4');

    map.addLayer({
        "id": "wins",
        "type": "line",
        "source": "weather",
        "source-layer": "RoadWeather",
        "layout": {
            "line-join": "round",
            "line-cap": "round"
        },
        "paint": {
            "line-color": {
                "property": "WINS",
                "stops": [
                    [0, '#28AD86'],
                    [10, '#28AD86'],
                    [10.1, '#E0B62C'],
                    [20.8, '#E0B62C'],
                    [20.9, '#FE4B3C'],
                    [28.5, '#FE4B3C'],
                    [28.6, '#8E71FF'],
                ]
            },
            "line-width": 6
        }
    }, 'e9424af07d8242adb4fa49abe40544b4');

    map.addLayer({
        "id": "road-highlight",
        "type": "line",
        "source": "weather",
        "source-layer": "RoadWeather",
        "layout": {
            "line-join": "round",
            "line-cap": "round"
        },
        "paint": {
            "line-color": "#00EDFF",
            "line-width": 6
        },
        "filter": ["==", "pid", pid]
    }, 'd39e3ae1f4b043a68042840967c60dd3');

    map.on('click', function (e) {
        var feature = map.queryRenderedFeatures(e.point, {
            layers: ['tem']
        });
        console.log(feature);

        if (feature[0]) {
            var properties = feature[0].properties;
            pid = properties.pid;
            console.log(pid);
            map.setFilter('road-highlight', ["==", "pid", pid]);
            let data = [properties.precipitation0, properties.precipitation1,
                properties.precipitation2, properties.precipitation3, properties.precipitation4,
                properties.precipitation5, properties.precipitation6, properties.precipitation7,
                properties.precipitation8, properties.precipitation9, properties.precipitation10,
                properties.precipitation11, properties.precipitation12, properties.precipitation13,
                properties.precipitation14, properties.precipitation15, properties.precipitation16,
            ]
            popupBox.setData(data, e);
        }
    });

    // map.on('moveend', function (e) {
    //     const center = map.getCenter();
    //     minemap.util.getJSON('http://minedata.cn/service/search/adminByPoint?token=a3622f2702c34957a160242d2eb0e508&location=' + center.lng + ',' + center.lat, function (error, data) {
    //         const areaName = data.data.areaname;
    //         const adcode = data.data.adcode;
    //         if (adcode != weatherChart.adcode) {
    //             minemap.util.getJSON('http://203.81.245.38:48082/weather/adminweather/' + adcode, function (error, data) {
    //                 if (error) {
    //                     console.log(error)
    //                 } else {
    //                     weatherChart = new WeatherBox('weather-chart', data, areaName, adcode);
    //                 }
    //             });
    //         }
    //     });
    // });

    closeLayer();
    roadConditionButton.className = 'weather-switch-selected';
    // map.setLayoutProperty('b519feeafff3466091df41876924bf21', 'visibility', 'visible');
    // map.setLayoutProperty('563da56af516487aa272c0bcc914815a', 'visibility', 'visible');  
    // map.setLayoutProperty('a459eaf51c9a4bdf85645de25a929420', 'visibility', 'visible');
    // map.setLayoutProperty('d7bb38190113411486f0dc41601f926a', 'visibility', 'visible');

    map.moveLayer('b519feeafff3466091df41876924bf21', topId);
    map.moveLayer('563da56af516487aa272c0bcc914815a', topId);
    map.moveLayer('a459eaf51c9a4bdf85645de25a929420', topId);
    map.moveLayer('d7bb38190113411486f0dc41601f926a', topId);

    document.getElementById('loading').style.display = 'none';
});

minemap.util.getJSON('http://203.81.245.38:48082/weather/adminweather/610102', function (error, data) {
    weatherChart = new WeatherBox('weather-chart', data, '西安市', 610102);
});
// minemap.util.getJSON('http://minedata.cn/service/search/adminByPoint?token=a3622f2702c34957a160242d2eb0e508&location=108.95,34.27', function (error, data) {
//     const areaName = data.data.areaname;
//     const adcode = data.data.adcode;
//     minemap.util.getJSON('http://203.81.245.38:48082/weather/adminweather/' + adcode, function (error, data) {
//         weatherChart = new WeatherBox('weather-chart', data, areaName, adcode);
//     });
// });

let temInfoObj = null;
let winsInfoObj = null;
let preInfoObj = null;

minemap.util.getJSON('http://203.81.245.38:48082/weather/weathertop10/tem', function (error, data) {
    const dataArr = data.data.rows[0].features
    temInfoObj = {
        "color1": "#00C0CE",
        "color2": "#FEC819",
        "unit": "温度（℃）",
        "array": [],
        callback: (coordinate) => {
            map.flyTo({
                center: coordinate,
                zoom: 15
            });
        }
    };
    dataArr.map((item) => {
        temInfoObj.array.push({
            "name": item.properties.name_zh,
            "value": item.properties.tem,
            "coordinate": item.geometry.coordinates[Math.ceil(item.geometry.coordinates.length / 2)]
        })
    });
    roadWeatherChart = new InfoBarList('road-weather-chart', temInfoObj);
});

minemap.util.getJSON('http://203.81.245.38:48082/weather/weathertop10/pre', function (error, data) {
    const dataArr = data.data.rows[0].features
    preInfoObj = {
        "color1": "#00C0CE",
        "color2": "#FEC819",
        "unit": "降水量（mm）",
        "array": [],
        callback: (coordinate) => {
            map.flyTo({
                center: coordinate,
                zoom: 15
            });
        }
    };
    dataArr.map((item) => {
        preInfoObj.array.push({
            "name": item.properties.name_zh,
            "value": Number(item.properties.pre).toFixed(2),
            "coordinate": item.geometry.coordinates[Math.ceil(item.geometry.coordinates.length / 2)]
        })
    });
});

minemap.util.getJSON('http://203.81.245.38:48082/weather/weathertop10/wins', function (error, data) {
    const dataArr = data.data.rows[0].features
    winsInfoObj = {
        "color1": "#00C0CE",
        "color2": "#FEC819",
        "unit": "风力(级)",
        "array": [],
        callback: (coordinate) => {
            map.flyTo({
                center: coordinate,
                zoom: 15
            });
        }
    };
    dataArr.map((item) => {
        winsInfoObj.array.push({
            "name": item.properties.name_zh,
            "value": item.properties.wins,
            "coordinate": item.geometry.coordinates[Math.ceil(item.geometry.coordinates.length / 2)]
        })
    });
});




const arr = [{
        name: '交通阻塞',
        value: 22
    },
    {
        name: '交通事故',
        value: 12
    },
    {
        name: '灾害',
        value: 3
    },
    {
        name: '交通规则改变',
        value: 25
    },
    {
        name: '道路作业',
        value: 23
    },
    {
        name: '车辆类型限制',
        value: 18
    }
];

const obj1 = {
    "color1": "#FF5500",
    "color2": "#EDCF6D",
    "array": [{
            "name": '广粤支路',
            "sub": '从汶水东路至粤秀路',
            "value": 23.5
        },
        {
            "name": '广粤支路',
            "sub": '从粤秀路至汶水东路',
            "value": 20.3
        },
        {
            "name": '何家湾路',
            "sub": '从国权北路至长江南路',
            "value": 19.4
        },
        {
            "name": '金汇路',
            "sub": '从程家桥路至吴中路',
            "value": 19.2
        },
        {
            "name": '新开河路',
            "sub": '从人民路至中山东二路',
            "value": 18.3
        },
        {
            "name": '东江阴街',
            "sub": '从跨龙路至柳市路',
            "value": 18.0
        },
        {
            "name": '新沪路',
            "sub": '从华灵路至沪太路',
            "value": 18.0
        },
        {
            "name": '柳市路',
            "sub": '从东江阴街至陆家浜路',
            "value": 18.0
        },
        {
            "name": '空港六路',
            "sub": '从沪青平公路至迎宾三路',
            "value": 17.7
        },
        {
            "name": '百色路',
            "sub": '从龙吴路至老沪闵路',
            "value": 16.8
        },
    ]
};

const obj2 = {
    "color1": "#00C0CE",
    "color2": "#FEC819",
    "unit": "温度（℃）",
    "array": [{
            "name": '许昌路',
            "value": 20.1
        },
        {
            "name": '杭州湾大道',
            "value": 19
        },
        {
            "name": '青浦路',
            "value": 19
        },
        {
            "name": '温虹路',
            "value": 18.2
        },
        {
            "name": '乌鲁木齐中路',
            "value": 17.4
        },
        {
            "name": '镇坪路',
            "value": 17
        },
        {
            "name": '程家桥路',
            "value": 16.8
        },
        {
            "name": '中潭路',
            "value": 16.2
        },
        {
            "name": '恒丰北路',
            "value": 15.5
        },
        {
            "name": '谈家渡路',
            "value": 15
        },
    ]
};

const legendObjRoad = {
    name: '实时路况',
    arrName: ['严重拥堵', '拥堵', '缓行', '畅通'],
    arrColor: ['#AD1717', '#E53434', '#FF9901', '#66CC01']
}

const legendObjTem = {
    name: '温度',
    arrName: ['0-10', '10-25', '25-30', '>30'],
    arrColor: ['#28AD86', '#E0B62C', '#FE4B3C', '#8E71FF']
}

const legendObjWins = {
    name: '风力',
    arrName: ['0-10', '10-20.8', '20.8-28.5', '>28.5'],
    arrColor: ['#28AD86', '#E0B62C', '#FE4B3C', '#8E71FF']
}

const legendObjPre = {
    name: '降水量',
    arrName: ['0-10', '10-25', '25-50', '>50'],
    arrColor: ['#28AD86', '#E0B62C', '#FE4B3C', '#8E71FF']
}

const incidentChart = new PieChart('incident-chart', arr);
const congestionChart = new InfoBarList('congestion-chart', obj1);
let roadWeatherChart = null;
let weatherChart = null;
const timeLine = new TimeLine('timeline-box', 16, (num) => {
    if (num === 0) {
        map.setPaintProperty('pre', 'line-color', {
            "property": "PRE",
            "stops": [
                [0, '#28AD86'],
                [10, '#28AD86'],
                [11, '#E0B62C'],
                [25, '#E0B62C'],
                [26, '#FE4B3C'],
                [50, '#FE4B3C'],
                [51, '#8E71FF']
        ]
        });
    } else {
        map.setPaintProperty('pre', 'line-color', {
            "property": "precipitation" + (num - 1),
            "stops": [
                [0, '#28AD86'],
                [10, '#28AD86'],
                [11, '#E0B62C'],
                [25, '#E0B62C'],
                [26, '#FE4B3C'],
                [50, '#FE4B3C'],
                [51, '#8E71FF']
        ]
        });
    }
});
timeLine.disappear();
const legend = new Legend('legend', legendObjRoad);
const popupBox = new Popup(popup, map);

const roadConditionButton = document.getElementById('road-condition-button');
const temButton = document.getElementById('tem-button');
const winsButton = document.getElementById('wins-button');
const rhButton = document.getElementById('rh-button');
const preButton = document.getElementById('pre-button');
const incidentButton = document.getElementById('incident-button');
let incidentBool = true;
incidentButton.addEventListener('click', () => {
    if (incidentBool) {
        map.setLayoutProperty('5a3ea454892d4824b622cdabb48950a2', 'visibility', 'none');
        incidentButton.className = 'weather-switch-not-selected';
        document.getElementById('incident-button-not').style.display = 'inline-block';
        document.getElementById('incident-button-sel').style.display = 'none';
        incidentBool = !incidentBool;
    } else {
        map.setLayoutProperty('5a3ea454892d4824b622cdabb48950a2', 'visibility', 'visible');
        incidentButton.className = 'weather-switch-selected';
        document.getElementById('incident-button-not').style.display = 'none';
        document.getElementById('incident-button-sel').style.display = 'inline-block';
        incidentBool = !incidentBool;
    }
});

roadConditionButton.addEventListener('click', () => {
    closeLayer();
    // map.setLayoutProperty('b519feeafff3466091df41876924bf21', 'visibility', 'visible');
    // map.setLayoutProperty('563da56af516487aa272c0bcc914815a', 'visibility', 'visible');
    map.moveLayer('b519feeafff3466091df41876924bf21', topId);
    map.moveLayer('563da56af516487aa272c0bcc914815a', topId);
    map.moveLayer('a459eaf51c9a4bdf85645de25a929420', topId);
    map.moveLayer('d7bb38190113411486f0dc41601f926a', topId);
    roadConditionButton.className = 'weather-switch-selected';
    legend.setData(legendObjRoad);
});

temButton.addEventListener('click', () => {
    closeLayer();
    // map.setLayoutProperty('tem', 'visibility', 'visible');
    map.moveLayer('tem', topId);
    temButton.className = 'weather-switch-selected';
    legend.setData(legendObjTem);
    roadWeatherChart = new InfoBarList('road-weather-chart', temInfoObj);
});

winsButton.addEventListener('click', () => {
    closeLayer();
    // map.setLayoutProperty('wins', 'visibility', 'visible');
    map.moveLayer('wins', topId);
    winsButton.className = 'weather-switch-selected';
    legend.setData(legendObjWins);    
    roadWeatherChart = new InfoBarList('road-weather-chart', winsInfoObj);
});

preButton.addEventListener('click', () => {
    closeLayer();
    // map.setLayoutProperty('pre', 'visibility', 'visible');
    // map.setLayoutProperty('road-highlight', 'visibility', 'visible');
    map.moveLayer('pre', topId);
    preButton.className = 'weather-switch-selected';
    timeLine.show();
    legend.setData(legendObjPre);
    roadWeatherChart = new InfoBarList('road-weather-chart', preInfoObj);
});

function closeLayer() {
    // map.setLayoutProperty('b519feeafff3466091df41876924bf21', 'visibility', 'none');
    // map.setLayoutProperty('563da56af516487aa272c0bcc914815a', 'visibility', 'none');
    // map.setLayoutProperty('a459eaf51c9a4bdf85645de25a929420', 'visibility', 'none');
    // map.setLayoutProperty('d7bb38190113411486f0dc41601f926a', 'visibility', 'none');
    map.moveLayer('b519feeafff3466091df41876924bf21', backgroundId);
    map.moveLayer('563da56af516487aa272c0bcc914815a', backgroundId);
    map.moveLayer('a459eaf51c9a4bdf85645de25a929420', backgroundId);
    map.moveLayer('d7bb38190113411486f0dc41601f926a', backgroundId);
    roadConditionButton.className = 'weather-switch-not-selected';

    // map.setLayoutProperty('pre', 'visibility', 'none');
    // map.setLayoutProperty('road-highlight', 'visibility', 'none');
    map.moveLayer('pre', backgroundId);
    preButton.className = 'weather-switch-not-selected';
    timeLine.disappear();

    // map.setLayoutProperty('tem', 'visibility', 'none');
    map.moveLayer('tem', backgroundId);
    temButton.className = 'weather-switch-not-selected';

    // map.setLayoutProperty('wins', 'visibility', 'none');
    map.moveLayer('wins', backgroundId);
    winsButton.className = 'weather-switch-not-selected';
}